<?php

class loginActions extends sfActions
{
    public function executeIndex(sfWebRequest $request)
    {
        $this->form = new UserSignInForm();
        
        if($request->isMethod('post'))
        {           
            // check for valid administrator login
            $user = $this->executeCheck($request);
            if(!$user)
            {
                $this->getUser()->setFlash('error', 'Wrong user_id or password!');
                $this->redirect('login/index');
            }
            else
            {
                $this->getUser()->getAttributeHolder()->clear();
                $this->getUser()->setAuthenticated(false);
                $this->getUser()->clearCredentials();
                
                if($user->getRole()->getTitle()=='administrator')
                {
                    $this->getUser()->setAuthenticated(true);
                    $this->getUser()->addCredential('admin');
                    $this->redirect('@article');
                }
                else
                {
                    $this->getUser()->setFlash('error', 'You have not suffiecient privilleges to login!');
                    $this->redirect('login/index');
                }
            }            
         }
         
    }

    public function executeLogout(sfWebRequest $request)
    {
        $this->getUser()->getAttributeHolder()->clear();
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->clearCredentials();
        $this->redirect('login/index');
    }

    public function executeLogin(sfWebRequest $request)
    {
        $this->redirect('login/index');
    }

   protected function executeCheck(sfWebRequest $request)
   {      
      $this->form = new UserSignInForm();
      return $this->processSignInForm($request, $this->form);
   }
   
   protected function processSignInForm($request, $form)
   {
      $form->bind($request->getParameter($form->getName()));

      if($form->isValid())
      {
          $user = UserPeer::checkUserNamePassword($form->getValues());

          // Check for valid User & Password
          if($user)
          {
            // Sign in & save the article form(if exist)
              return $user;
          }
          else
          {
              return false;
          }
      }
   }
}

?>